package top.wbhzx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.wbhzx.mapper.AdminMapper;
import top.wbhzx.mapper.DirMapper;
import top.wbhzx.mapper.FileMapper;
import top.wbhzx.pojo.*;
import top.wbhzx.service.UserService;
import top.wbhzx.utils.HttpData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private AdminMapper AdminMapper;
	@Autowired
	private FileMapper fileMapper;
	@Autowired
	private DirMapper dirMapper;
	
	/**
	 * 注册接口
	 * @param username
	 * @param password
	 * @param phone
	 * @return 
	 */
	@RequestMapping(value="/register.json", method=RequestMethod.POST)
	public Object userRegister(@RequestParam String username, @RequestParam String password, @RequestParam String phone) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setPhone(phone);
 		System.out.println(user);

		//HashMap<String, String> map = new HashMap<String, String>();
		HttpData map = new HttpData();
		
		User qUser = new User();
		qUser.setPhone(user.getPhone());
		//验证手机或邮箱的唯一性
		try {
			if(userService.selListByPo(qUser).size() > 0) {
				//map.put("smg", "手机号已被注册");
				map.getMsg().setMsgText("手机号已被注册");
				return JSONArray.toJSONString(map);
			}
		} catch (Exception e) {
			//map.put("smg", "系统错误");
			map.getMsg().setMsgText("系统错误");
			e.printStackTrace();
		}
		
		//验证账号唯一性
		qUser.setUsername(user.getUsername());
		qUser.setPhone(null);
		try {
			if(userService.selListByPo(qUser).size() > 0) {
				//map.put("smg", "用户名已被注册");
				map.getMsg().setMsgText("用户名已被注册");
				return JSONArray.toJSONString(map);
			}
		} catch (Exception e) {
//			map.put("smg", "系统错误");
			map.getMsg().setMsgText("系统错误");
			e.printStackTrace();
		}
		
		//初始化户用数据
		user.setRegisterTime(System.currentTimeMillis());
		user.setState(1);
		user.setRole(1);
		try {
			if(userService.addOne(user) > 0) {
//				map.put("smg", "注册成功");
				//查询用户id
				Integer newId = userService.selListByPo(new User(user.getUsername(),null,null)).get(0).getId();
				//创建基础文件夹
				Dir dir = new Dir();
				dir.setDirName("我的文件");
				dir.setDirParentId(1);
				dir.setDirPath("/root/"+user.getUsername());
				dir.setUserId(newId);
				dirMapper.insert(dir);
				map.getData().put("username", user.getUsername());
				map.getMsg().setMsgText("注册成功");
			}
		} catch (Exception e) {
			map.getMsg().setMsgText("系统错误");
			e.printStackTrace();
		}
		
			return JSONArray.toJSONString(map);
	}

	/**
	 * 登录接口
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/login.json", method = RequestMethod.POST)
	public Object login(@RequestParam String username, @RequestParam String password) {
		
		HttpData result = new HttpData();
		
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		List<User> userlist = null;
		try {
			userlist = userService.selListByPo(user);	
		} catch (Exception e) {
			e.printStackTrace();
			result.getMsg().setMsgText("系统错误");
			return JSONArray.toJSONString(result);
		}
		
		if(userlist.size() > 0 && userlist.get(0).getState() != 0) {
			result.getMsg().setMsgText("登录成功");
			result.getData().put("user", userlist.get(0));
		}else{
			result.getMsg().setMsgText("登录失败");
		}
			
		return JSONArray.toJSONString(result);
	}
	
	@RequestMapping(value = "/adminLogin.json")
	public Object login2(@RequestParam String username, @RequestParam String password) {
			
			HttpData result = new HttpData();
			
			Admin admin = new Admin();
			admin.setAdminName(username);
			admin.setPassword(password);
			
			List<Admin> userlist = null;
			try {
				userlist = AdminMapper.selectListByPo(admin);
			} catch (Exception e) {
				e.printStackTrace();
				result.getMsg().setMsgText("系统错误");
				return JSONArray.toJSONString(result);
			}
			
			if(userlist.size() > 0 && userlist.get(0).getState() != 0) {
				result.getMsg().setMsgText("登录成功");
				result.getData().put("user", userlist.get(0));
			}else{
				result.getMsg().setMsgText("登录失败");
			}
				
			return JSONArray.toJSONString(result);
		}
	
	@RequestMapping(value = "/add.json")
	public Object add(@RequestBody HashMap<String,HashMap<String, Object>> map) {
		
		HttpData result = new HttpData();
		//判断所操作的类
		Integer key = (Integer)map.get("info").get("objCode");
		
		//准备实体类
		Object object = null; 
		switch (key) {
		case 1:
			object = new User();
			break;
		case 2:
			object = new Admin();
			break;
		case 3:
			object = new File();
			break;
		case 4:
			object = new Dir();
			break;
		default:
			result.getMsg().setMsgText("objCode有误");
			return JSONArray.toJSONString(result);
		}
		
		//为实体类设值
		try {
			AttrUtil.setAttributes(object, map.get("obj"));
		} catch (IllegalArgumentException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (SecurityException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		}
		
		if(result.getMsg().getMsgText().equals("参数有误")) {
			return JSONArray.toJSONString(result);
		}
		
		try {
			switch (key) {
				case 1:
					User u = (User)object;
					u.setRegisterTime(System.currentTimeMillis());
					Integer count = userService.addOne(u);
					result.getData().put("count", count);
					if(count > 0) {
						Integer uId = userService.selListByPo(new User(u.getUsername(),null,null)).get(0).getId();
						Dir dir = new Dir();
						dir.setDirName("我的文件");
						dir.setDirParentId(1);
						dir.setDirPath("/root/"+u.getUsername());
						dir.setUserId(uId);
						dirMapper.insert(dir);
					}
					break;
				case 2:
					Admin ad = (Admin)object;
					ad.setRegisterTime(System.currentTimeMillis());
					result.getData().put("count", AdminMapper.insertSelective((Admin)object));
					break;
				case 3:
					File f = (File)object;
					f.setFileUploadTime(System.currentTimeMillis());
					result.getData().put("count",fileMapper.insertSelective((File)object));
					break;
				case 4:
					result.getData().put("count", dirMapper.insertSelective((Dir)object));
					break;
				default:
					result.getMsg().setMsgText("objCode有误");
					return JSONArray.toJSONString(result);
			}
			
			result.getMsg().setMsgText("增加成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.getMsg().setMsgText("系统错误,可能参数不足");
		}
		
		return JSONArray.toJSONString(result);
	}
	
	@RequestMapping(value = "/remove.json")
	public Object remove(@RequestBody HashMap<String,HashMap<String, Object>> map) {
		HttpData result = new HttpData();
		
		//判断所操作的类
		Integer key = (Integer)map.get("info").get("objCode");
		
		Integer[] ids = JSONArray.toJavaObject((JSON)map.get("obj").get("ids"), Integer[].class);
		
		//执行删除
		try {
			switch (key) {
			case 1:
				result.getData().put("count", userService.removeListById(ids));
				break;
			case 2:
				result.getData().put("count", AdminMapper.deleteListByPrimaryKey(ids));
				break;
			case 3:
				result.getData().put("count", fileMapper.deleteListByPrimaryKey(ids));
				break;
			case 4:
				result.getData().put("count", dirMapper.deleteListByPrimaryKey(ids));
				break;
			default:
				result.getMsg().setMsgText("objCode有误");
				return JSONArray.toJSONString(result);
			}
			result.getMsg().setMsgText("执行通过");
		} catch (Exception e) {
			e.printStackTrace();
			result.getMsg().setMsgText("系统错误");
		}
		
		return JSONArray.toJSONString(result);
	}
	
	@RequestMapping(value = "/update.json")
	public Object update(@RequestBody HashMap<String,HashMap<String, Object>> map) {
		HttpData result = new HttpData();
		
		//判断所操作的类
		Integer key = (Integer)map.get("info").get("objCode");
		
		//准备实体类
		Object object = null; 
		switch (key) {
		case 1:
			object = new User();
			break;
		case 2:
			object = new Admin();
			break;
		case 3:
			object = new File();
			break;
		case 4:
			object = new Dir();
			break;
		default:
			result.getMsg().setMsgText("objCode有误");
			return JSONArray.toJSONString(result);
		}
		
		//为实体类设值
		try {
			AttrUtil.setAttributes(object, map.get("obj"));
		} catch (IllegalArgumentException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (SecurityException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		}
		
		if(result.getMsg().getMsgText().equals("参数有误")) {
			return JSONArray.toJSONString(result);
		}
		
		try {
			
			switch (key) {
			case 1:
				result.getData().put("count", userService.modifyOnById((User)object));
				break;
			case 2:
				result.getData().put("count", AdminMapper.updateByPrimaryKeySelective((Admin)object));
				break;
			case 3:
				result.getData().put("count", fileMapper.updateByPrimaryKeySelective((File)object));
				break;
			case 4:
				result.getData().put("count", dirMapper.updateByPrimaryKeySelective((Dir)object));
				break;
			default:
				break;
			}
			result.getMsg().setMsgText("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.getMsg().setMsgText("系统错误");
		}
		
		return JSONArray.toJSONString(result);
	}
	
	@RequestMapping(value = "/query.json")
	public Object query(@RequestBody HashMap<String,HashMap<String, Object>> map, HttpServletResponse response) {
		HttpData result = new HttpData();
		
		//判断所操作的类
		Integer key = (Integer)map.get("info").get("objCode");
		
		//准备实体类
		Object object = null; 
		switch (key) {
		case 1:
			object = new User();
			break;
		case 2:
			object = new Admin();
			break;
		case 3:
			object = new File();
			break;
		case 4:
			object = new Dir();
			break;
		default:
			result.getMsg().setMsgText("objCode有误");
			return JSONArray.toJSONString(result);
		}
		
		//为实体类设值
		if(map.get("obj") != null)
		try {	
			AttrUtil.setAttributes(object, map.get("obj"));
		} catch (IllegalArgumentException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		} catch (SecurityException e1) {
			result.getMsg().setMsgText("参数有误");
			e1.printStackTrace();
		}
		
		//检查参数有误
		if(result.getMsg().getMsgText().equals("参数有误")) {
			return JSONArray.toJSONString(result);
		}
		
		try {
			switch (key) {
			case 1:
				result.getData().put("list", userService.selListByPo((User)object));
				break;
			case 2:
				result.getData().put("list", AdminMapper.selectListByPo((Admin)object));
				break;
			case 3:
				result.getData().put("list", fileMapper.selectListByPo((File)object));
				break;
			case 4:
				result.getData().put("list", dirMapper.selectListByPo((Dir)object));
				break;
			default:
				break;
			}
			
			result.getMsg().setMsgText("查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.getMsg().setMsgText("系统错误");
		}
		
		return JSONArray.toJSONString(result);
	}
	
	@RequestMapping(value = "/queryFD.json")
	public Object queryFD(@RequestBody HashMap<String, Object> map) {
		Integer dirId = (Integer) map.get("dirId");
		
		HttpData result = new HttpData();
		
		List<FD> fds = new ArrayList<FD>();
		
		File file = new File();
		file.setDirId(dirId);
		List<File> fileLise = fileMapper.selectListByPo(file);
		for(File f : fileLise) {
			FD fd = new FD();
			fd.setId(f.getId()+1000);
			fd.setPId(f.getDirId());
			fd.setName(f.getFileName());
			fd.setSize(f.getFileSize());
			fd.setTime(f.getFileUploadTime());
			fd.setFilestatus(f.getFileStatus());
			fd.setIsFile(true);
			fds.add(fd);
		}
		
		
		
		Dir dir = new Dir();
		dir.setDirParentId(dirId);
		List<Dir> dirList = dirMapper.selectListByPo(dir);
		for(Dir d : dirList) {
			FD fd = new FD();
			fd.setId(d.getId());
			fd.setPId(d.getDirParentId());
			fd.setName(d.getDirName());
			fd.setSize(null);
			fd.setTime(null);
			fd.setFilestatus(null);
			fd.setIsFile(false);
			fd.setPath(d.getDirPath());
			fds.add(fd);
		}
		result.getData().put("list", fds);
		return JSONArray.toJSONString(result);
	}
	
}
